class Minify
  module Cached
    def cached_javascript_includes
      js_file = ::Minify.cache_name(:js)
      if File.exists?(File.join(RAILS_ROOT, "public/javascripts", js_file))
        # js_file = javascript_path(js_file).gsub(/\?.*$/, '')
        javascript_include_tag js_file
      else
        javascript_include_tag *::Minify::files(:js)
      end
    end

    def cached_stylesheet_includes
      css_file = ::Minify.cache_name(:css)
      if File.exists?(File.join(RAILS_ROOT, "public/stylesheets", css_file))
        # css_file = stylesheet_path(css_file).gsub(/\?.*$/, '')
        stylesheet_link_tag css_file
      else
        stylesheet_link_tag *::Minify::files(:css)
      end
    end
  end
    
  def self.emit(type)
    klass, fileslist = :js == type.to_sym ? [JsMin, files(type)] : [CssMin, files(type)]
    File.open(file_path(type), "w") do |f|
      f.write fileslist.map { |file| klass.minify(IO.read("#{dir(type)}/#{file}")) }.join
    end
  end

  def self.file_path(type)
    File.join(dir(type), cache_name(type))
  end

  CACHE_NAME = "eusden" unless defined? CACHE_NAME
  def self.cache_name(type)
    "#{CACHE_NAME}.#{type}"
  end

  def self.dir(type)
    File.join(
      RAILS_ROOT,
      "public",
      :js == type.to_sym ? "javascripts" : "stylesheets"
    )
  end

  def self.files(type)
    list = []
    Dir.open(dir(type)) do |directory|
      directory.each do |file|
        if file =~ /.+\.#{type.to_s}$/i && file != cache_name(type)
          list << file.downcase
        end
      end
    end
    reorder(type, list)
  end
  
  def self.reorder(type, list)
    if :js == type.to_sym
      reordered = []
      JS_DEPENDENCY.each do |filename|
        d = list.delete("#{filename}.js")
        reordered << d if d
      end
      reordered.concat(list)
    else
      list
    end
  end
  
  JS_DEPENDENCY = %w(
    prototype
    effects
    builder
    application
    swfupload
    lightbox
  ) unless defined? JS_DEPENDENCY 
  
end
